package com.tucc.hello.leetcode.no1_400.no1_200.no81_100.no86;

import com.tucc.hello.leetcode.common.ListNode;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head = ListNode.of(3, 1);
        int x = 3;
        ListNode newHead = solution.partition(head, x);
        ListNode.print(newHead);
    }

    public ListNode partition(ListNode head, int x) {
        ListNode pre = null;
        ListNode pTail = null;
        ListNode after = null;
        ListNode aTail = null;
        ListNode tail = head;
        while (tail != null) {
            if (tail.val < x) {
                if (pre == null) {
                    pre = tail;
                    pTail = tail;
                } else {
                    pTail.next = tail;
                    pTail = tail;
                }
            } else {
                if (after == null) {
                    after = tail;
                    aTail = tail;
                } else {
                    aTail.next = tail;
                    aTail = tail;
                }
            }
            tail = tail.next;
        }
        ListNode newHead = null;
        if (after != null) {
            aTail.next = null;
            newHead = after;
        }
        if (pre != null) {
            pTail.next = newHead;
            newHead = pre;
        }
        return newHead;
    }
}
